<?php

declare(strict_types=1);

namespace App\Lib;

use Firebase\JWT\JWT;

class JwtToken
{
    public static $data = [];   //返回結果
    public static $exp = 28800;  //token的過期時間
    public static $overtime = 25920000;  //刷新token的過期時間


    //生成授權token和刷新的token
    /**
     * @param integer $user_id 用户id
     * @param string $account  用户名或openid
     * @param string $flag  前台后台区分  1后台  2前后
     * @return array
     * @Description
     * @example
     * @author wuxian
     * @since 2020-04-17
     */
    public static function authorizations(int $user_id, string $account, string $flag = '1'): array
    {
        $access_token = self::createJwt($user_id, $account, self::$exp, $flag);
        $refresh_token = self::createJwt($user_id, $account, self::$overtime, $flag);//生成刷新token
        return ['token' => $access_token, 'refresh_token' => $refresh_token];
    }

    //生成token
    public static function createJwt(int $user_id, string $account, int $exp = 0, string $flag = '1'): string
    {
        $key = config('web.jwt_key',''); //jwt的签发密钥，验证token的时候需要用到
        $time = time();
        $nbf = $time;
        empty($exp) ? $exp = self::$exp : '';
        $expire = $time + $exp;
        $token = array(
            "iss" => $flag,  //签发者 可以为空
            "aud" => "", //面象的用户，可以为空
            "iat" => $time, //签发时间
            "nbf" => $nbf, //在什么时候jwt开始生效  （这里表示生成10秒后才生效）
            "exp" => $expire, //token 过期时间
            "uid" => $user_id, //记录的userid的信息
            'account' => $account, // 用户账号
        );
        $jwt = JWT::encode($token, $key);
        return $jwt;
    }

    //檢查token
    public static function checkToken(array $header): array
    {
        if (!isset($header[0])) {
            self::$data = [
                'errCode' => 4001,
                'msg' => '沒有Token值'
            ];
            return self::$data;
        }
        $checkJwtToken = static::verifyJwt($header[0]);
        self::$data = $checkJwtToken;
        return $checkJwtToken;
        // if (empty($checkJwtToken['error'])) {
        //     return true;
        // }
        // return false;

    }

    //校验jwt权限API
    protected static function verifyJwt(string $jwt): array
    {
        $key = config('web.jwt_key','');
        // JWT::$leeway = 3;
        try {
            $jwtAuth = json_encode(JWT::decode($jwt, $key, array('HS256')));
            $authInfo = json_decode($jwtAuth, true);
       
            return ['errCode' => 0, 'data' => $authInfo];

        } catch (\Firebase\JWT\SignatureInvalidException $e) {
            return [
                'errCode' => 4002,
                'msg' => 'Token无效'
            ];
        } catch (\Firebase\JWT\ExpiredException $e) {
            return [
                'errCode' => 4003,
                'msg' => 'Token过期'
            ];

        } catch (Exception $e) {
            return [
                'errCode' => 4004,
                'msg' => $e->getMessage()
            ];
        }
    }

    /**
     * 刷新重新生成并返回token
     * @return array
     */
    public static function refreshToken(string $refresh_token): array
    {
        $key = config('web.jwt_key','');
        try {
            $jwtAuth = json_encode(JWT::decode($refresh_token, $key, array('HS256')));
            $authInfo = json_decode($jwtAuth, true);
            return ['errCode' => 0, 'data' => self::createJwt($authInfo['uid'], $authInfo['account'], self::$exp, $authInfo['iss']), 'msg' => ''];

        } catch (\Firebase\JWT\SignatureInvalidException $e) {
            return [
                'errCode' => 4002,
                'msg' => 'Token无效'
            ];
        } catch (\Firebase\JWT\ExpiredException $e) {
            return [
                'errCode' => 4003,
                'msg' => 'Token过期'
            ];

        } catch (Exception $e) {
            return [
                'errCode' => 4004,
                'msg' => $e->getMessage()
            ];
        }
    }


}